﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FanaticRock.Core.DI;
using FanaticRock.Core.Helpers;
using FanaticRock.Core.ServiceInterfaces;
using FanaticRock.Models;
using Microsoft.Win32;
using System.IO;

namespace FanaticRock.ViewModels.OptionSettingConfig
{
    public partial class OptionSettingConfigViewModel : ObservableObject
    {
        #region fields

        private ILocalDbService _localDbService;

        #endregion

        #region props

        public string DownloadPath { get => _downloadPath; set => SetDownloadPath(value); }
        private string _downloadPath;


        #endregion

        #region ctors

        public OptionSettingConfigViewModel(ILocalDbService localDbService)
        {
            _localDbService = localDbService;

            var appOptionSettingOption = localDbService.GetByIdAsync<AppOptionSettingOption>(AppOptionSettingOption.Key).GetAwaiter().GetResult();
            if (appOptionSettingOption == null)
                appOptionSettingOption = new AppOptionSettingOption() { DownloadPath = Path.Combine(Environment.CurrentDirectory, "datadir")};
            DownloadPath = appOptionSettingOption.DownloadPath;
        }

        #endregion

        #region methods

        private void SetDownloadPath(string value)
        {
            _downloadPath = value;
            OnPropertyChanged(nameof(DownloadPath));

        }

        [RelayCommand]
        private async void ChangedDownloadPath()
        {
            var dialog = new OpenFolderDialog();
            if (dialog.ShowDialog() == true)
            {
                DownloadPath = dialog.FolderName;

                var appOptionSettingOption = Export();
                await _localDbService.UpsertAsync(appOptionSettingOption);
            }
        }

        private AppOptionSettingOption Export()
        {
            return new AppOptionSettingOption()
            {
                DownloadPath = DownloadPath,
            };
        }


        [RelayCommand]
        private void GotoBilibili()
        {
            ProcessHelper.Start(@"https://space.bilibili.com/337176361");
        }

        [RelayCommand]
        private void GotoGitee()
        {
            ProcessHelper.Start(@"https://gitee.com/fanbal");
        }
        #endregion
    }
}
